import {searchPoetry} from '../services/poet.js'

export default {

  namespace: 'search',

  state: {
    searchContent: '',
    lastId: 0,
    containNext: false,
    poetryList: []
  },

  subscriptions: {
    setup({dispatch, history}) {  // eslint-disable-line
    },
  },

  effects: {
    // 订阅服务，传入邮箱地址和昵称
    * queryPoetry({payload}, {call, put}) {
      const res = yield call(searchPoetry, payload);
      console.log("res: ", res);

      const apps = {
        list: res.data.result,
        content: payload.content,
      };

      yield put({
        type: 'save',
        payload: apps,
      });
    },
  },

  reducers: {
    /**
     * 首页查询成功，然后将后端返回的诗词写入list中,供前端渲染
     * @param state
     * @param apps
     * @returns {{apps: *, poetryList: Uint8Array | any[] | Int32Array | Uint16Array | Uint32Array | Float64Array | *}}
     */
    save(state, {payload: apps}) {
      let list = apps.list.map(app => {
          return {
            id: app.id,
            title: app.title,
            author: app.author,
            content: app.content,
            dynasty: app.dynasty,
          }
        }
      );

      if (state.searchContent === apps.content) {
        list = state.poetryList.concat(list);
      }

      let next = apps.list.length === 10;
      let lastId = 0;
      if (next) {
        lastId = apps.list[apps.list.length - 1].id;
      }

      // console.log(JSON.stringify(list));
      return {
        ...state, apps,
        poetryList: list,
        lastId: lastId,
        containNext: next,
        searchContent: apps.content
      };
    },
  },

};
